package servlet;

import dao.UserDao;
import entity.Product;
import entity.User;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;


@WebServlet(urlPatterns = "/User")
public class UserService extends BasicServlet {

    //用户登录
    public String userLogin(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        String userName = request.getParameter("username"), password = request.getParameter("password");
        try {
            User user = UserDao.getUser(userName,password);
            if(user == null) {
                request.setAttribute("loginResult","该用户不存在");
                request.getRequestDispatcher("/page/login.jsp");
            }else {
                session.setAttribute("user",user);
                response.sendRedirect("/");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Success";
    }

    //用户注册
    public String userRegister(HttpServletRequest request,HttpServletResponse response){
        String result = this.findUser(request,response);
        if(result.equals("Success")){
            request.setAttribute("success",false);
            try {
                request.getRequestDispatcher("/page/register.jsp").forward(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "Error";
        }
        String phone = request.getParameter("phone"),password = request.getParameter("password"),nickName = request.getParameter("nickName");
        int success = UserDao.registerUser(phone,password,nickName);
        try {
            if(success > 0)request.setAttribute("success",true);
            request.getRequestDispatcher("/page/register.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Success";
    }

    //用户是否存在
    public String findUser(HttpServletRequest request,HttpServletResponse response){
        String phone = request.getParameter("phone");
        boolean result = false;
        try {
            result = UserDao.findUser(phone);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result == true ? "Success" : "Error";
    }

    //退出登录
    public String userQuit(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession(false);
        session.removeAttribute("user");
        try {
            response.sendRedirect("/");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "用户退出登录";
    }

}
